<?php

use console\db\Migration;
use yii\db\Query;
use yii\helpers\Console;

/**
 * 追加泰山号动态点赞
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000008_t_sns_dynamic_like_tsline_append extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_like}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%ts_user_like}}')
        ->where(['model' => 'dynamic'])
        ->orderBy(['created_at' => SORT_ASC]);
        $this->handleProgress($query, [$this, 'evenDule'], null, Yii::$app->olddb);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if (!$data['model_id']) {
            return false;
        }
        $dynamicid = (new Query())->from('{{%sns_dynamic}}')->select('id')->where([
            'topic_id' => $data['model_id'],
            'deleted_at' => 0,
        ])->scalar();
        if (!$dynamicid) {
            return false;
        }
        $data['dynamic_id'] = $dynamicid;
        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $temp = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            $temp[] = [
                'user_id' => $row['user_id'],
                'dynamic_id' => $row['dynamic_id'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
            ];
        }
        if (empty($temp)) {
            return;
        }
        $migration->db->createCommand()->batchInsert($migration->tableName, [
            'user_id',
            'dynamic_id',
            'created_at',
            'updated_at',
        ], $temp)->execute();
    }

}
